package cn.scu.ne04jdemo.controller;


import cn.scu.ne04jdemo.dao.EDao;
import cn.scu.ne04jdemo.entitiy.Enterprise;
import cn.scu.ne04jdemo.entitiy.Job;
import cn.scu.ne04jdemo.entitiy.LinkInfo;
import cn.scu.ne04jdemo.service.EService;
import net.sf.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;

@RestController
@RequestMapping("/api")
public class EController {

    @Autowired
    EService eService;


    @GetMapping("/allE")
    public List<Enterprise> getAllE(){
        return eService.getAllE();
    }
    @GetMapping("/allJ")
    public List<Job> getAllJ(){
        return eService.getAllJ();
    }
    @GetMapping("/getE/{name}")
    public Enterprise getEByName(@PathVariable("name") String name){
        return eService.getEByName(name);
    }

    @GetMapping("/getJ/{name}")
    public Job getJByName(@PathVariable("name") String name){
        return eService.getJByName(name);
    }

    @PostMapping("/addE")
    public String addE(@RequestBody List<Enterprise> enterprise){
        for(Enterprise e: enterprise) {
            Integer x = new Random().nextInt(3);
            if(x % 2 == 0){
                e.setTag("核心");
            }else {
                e.setTag("非核心");
            }

            eService.insertE(e);
        }
        return "ok";
    }

    @PostMapping("/addJ")
    public String addJ(@RequestBody Map<String,Object> param){
        Object jobs = param.get("jobs");
        Object lname = param.get("lname");
        JSONArray jsonArr = JSONArray.fromObject(jobs);
        ArrayList<Job> datas = (ArrayList<Job>) JSONArray.toCollection(jsonArr, Job.class);
        //System.out.println(datas);
        //System.out.println(lname);

        for(Job job: datas){
            Integer x = new Random().nextInt(100);
            job.setLname(String.valueOf(lname));
            job.setJindu(x);
            eService.insertJ(job);
        }
        return "ok";
    }

    @PostMapping("/updateE")
    public String updateE(@RequestBody Enterprise enterprise){
        //System.out.println(enterprise);
        eService.updateE(enterprise);
        return "ok";
    }

    @PostMapping("/updateJ")
    public String updateJ(@RequestBody Job job){
        //System.out.println(job);
        eService.updateJ(job);
        return "ok";
    }

    @GetMapping("/getAllL")
    public List<LinkInfo> getAllL(){
        return eService.getAllL();
    }

    @GetMapping("/deleteE/{id}")
    public String deleteE(@PathVariable("id") Integer id){
        eService.deleteE(id);
        return "ok";
    }

    @GetMapping("/deleteJ/{id}")
    public String deleteJ(@PathVariable("id") Integer id){
        eService.deleteJ(id);
        return "ok";
    }

}
